#!/usr/bin/python
# @Time  : 2020/4/20 14:37
# @Author: LOUIE
# @Desc  : 封装HTTP请求库
from requests.exceptions import MissingSchema, InvalidSchema, InvalidURL
from utils.logger import log
from utils.tools import print_request_log
import requests
import json
import time


class HttpRequest(object):

    def __init__(self):
        self.session = requests.session()

    def __call__(self, method, url, name, **kwargs):
        """
        示例，可以直接通过类对象实例直接调用此方法
        request = HttpRequests()
        response = request(method, url, data)
        """
        return self.send_request(url, method, name, **kwargs)

    def send_request(self, method, url, name, **kwargs):
        """
        http 请求方法
        :param method: 请求方法
        :param url: 请求地址
        :param name: 接口名称
        :return: response: 响应体
        """
        identifier = ' = ' * 6

        print_request_log(name, method, url, kwargs)

        kwargs.setdefault("timeout", 30)

        start_timestamp = time.time()
        response = self.session.request(method, url, **kwargs)      # 需要定义params、data、json、file等传参格式
        response_time_ms = round((time.time() - start_timestamp) * 1000, 2)

        try:
            response.raise_for_status()
            log.info(
                f'{identifier} response detail {identifier}'
                f'\n{json.dumps(response.json(), indent=4, ensure_ascii=False)}'
            )
        except (MissingSchema, InvalidSchema, InvalidURL) as ex:
            raise ex
        else:
            log.info(
                f"status code: {response.status_code},  "
                f"response time(ms): {response_time_ms} ms"
            )
        return response


if __name__ == '__main__':
    urls = 'https://open.shiguangkey.com/api/udb/login/standard'
    header = {
        "content-type": "application/x-www-form-urlencoded",
        "terminaltype": "4"
    }
    methods = 'post'
    data = {
        'account': 'm15131424735',
        'password': 'xu9o8rj118541WgRNyP7DA'
    }
    res = HttpRequest().send_request(method=methods, url=urls, name="LOUIE测试接口", headers=header, data=data)
